package com.sjgl.esdn.utils;

/**
 * @Author: cjb
 * @Date: 2022-09-01 10:12
 **/
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @Version 1.0
 * @Author:cjb
 * @Date:2022/8/15
 * @Content:
 */
public class FileUtilsESDN {

    /**
     * 把一个文件转化为byte字节数组。
     *
     * @return byte[]
     */
    public static byte[] fileConvertToByteArray(String url) {
        byte[] data = null;

        File file = new File(url);
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            int len;
            byte[] buffer = new byte[1024];
            while ((len = fis.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }

            data = baos.toByteArray();

            fis.close();
            baos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return data;
    }
    public static String fileToBase64(String path) {
        String base64 = null;
        InputStream in = null;
        try {
            File file = new File(path);
            in = new FileInputStream(file);
            byte[] bytes = new byte[(int) file.length()];
            in.read(bytes);
            base64 = new String(Base64.encodeBase64(bytes),"UTF-8");
            System.out.println("将文件["+path+"]转base64字符串:"+base64);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;
    }

    public static String saveFile(MultipartFile file,String filePath,String fileName){
        if (file.isEmpty()){
            return "未选择文件";
        }
        File temp = new File(filePath);
        if (!temp.exists()){
            temp.mkdirs();
        }
        File localFile = new File(filePath + fileName);
        try {
            //把上传的文件保存至本地
            file.transferTo(localFile);
            System.out.println(file.getOriginalFilename()+" 上传成功");
        }catch (IOException e){
            e.printStackTrace();
            return "上传失败";
        }
        return "ok";
    }
}

